angular.module('chat.services', [])
/**
 *  处理会话名
 */
.filter('chatName', function () {
  return function (chat) {
    if (!chat) return;

    var otherId = _.without(chat.users, Meteor.userId())[0];
    var otherUser = Meteor.users.findOne(otherId);
    var hasName = otherUser && otherUser.profile && otherUser.profile.name;
    return hasName ? otherUser.profile.name : '无名氏';
  };
})
/**
 * 处理会话头像
 */
.filter('chatPicture', function () {
  return function (chat) {
    if (!chat) return;

    var otherId = _.without(chat.userIds, Meteor.userId())[0];
    var otherUser = Meteor.users.findOne(otherId);
    var hasPicture = otherUser && otherUser.profile && otherUser.profile.avatar;

    return hasPicture ? otherUser.profile.avatar : '/img/user-default.svg';
  };
})
.directive('input', function ($timeout) {
  var directive =  {
    restrict: 'E',
    scope: {
      'returnClose': '=',
      'onReturn': '&',
      'onFocus': '&',
      'onBlur': '&'
    },
    link: link
  };
  return directive;
  function link (scope, element, attrs) {
    element.bind('focus', function (e) {
      if (scope.onFocus) {
        $timeout(function () {
          scope.onFocus();
        });
      }
    });

    element.bind('blur', function (e) {
      if (scope.onBlur) {
        $timeout(function () {
          scope.onBlur();
        });
      }
    });

    element.bind('keydown', function (e) {
      if (e.which == 13) {
        if (scope.returnClose) {
          element[0].blur();
        }

        if (scope.onReturn) {
          $timeout(function () {
            scope.onReturn();
          });
        }
      }
    });
  }
})
.service("ChatService", function($rootScope,$timeout,$ionicScrollDelegate) {
  this.sendMessage = function(scope){
  
    if (_.isEmpty(scope.data.content)) return;

    var procData = angular.copy(scope.data);
    procData.type = 'text';
    procData.user = {
			_id : $rootScope.currentUser._id,
			name : $rootScope.currentUser.profile.name
		};
		procData.chat_id = scope.theSession._id;
  
    $ionicScrollDelegate.scrollBottom(true);
  
    scope.data={};
  
    $timeout(function() {
      Meteor.call('newMessage', procData, function(error) {
        if (error) {
          console.log(error);
        }else{
        }
      });
    }, 1);
  };
});
